package com.saatcioglu.android.sarkiyigoster;

import android.app.Service;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.IBinder;
import android.os.RemoteException;

import com.android.music.IMediaPlaybackService;

public class MusicStatusFetcher extends Service {
	private final Intent mIntentMusicPlayer = new Intent().setClassName(
			"com.android.music", "com.android.music.MediaPlaybackService");
	
	@Override
	public void onStart(Intent intent, int startId) {
		super.onStart(intent, startId);
		bindService(mIntentMusicPlayer, new ServiceConnection() {
			public void onServiceConnected(ComponentName comp, IBinder binder) {
				String artist = null;
				String song = null;
				try {
					IMediaPlaybackService mPlaybackService  = IMediaPlaybackService.Stub.asInterface(binder);
					artist = mPlaybackService.getArtistName();
					song = mPlaybackService.getTrackName();
				} catch (RemoteException e) {
				} finally {
					SharedPreferences sharedPreferences = MusicStatusFetcher.this.
					getSharedPreferences(SarkiyiGoster.SHARED_PREFERENCE, Context.MODE_PRIVATE);
					Editor editor = sharedPreferences.edit();
					editor.putString(SarkiyiGoster.ARTIST, artist);
					editor.putString(SarkiyiGoster.SONG, song);
					editor.commit();
				}
				MusicStatusFetcher.this.unbindService(this);
			}
			
			public void onServiceDisconnected(ComponentName comp) {
			}
			}, 0);
	}

	@Override
	public IBinder onBind(Intent intent) {
		return null;
	}
}
